<template>
  <scroll-view>
    <div :style="bottomStaySpace()" class="wrap">
      <div class="step">
        <up-steps active-color="#1890FF" current="0" inactive-color="#DEDFE2">
          <up-steps-item title="营业执照" />
          <up-steps-item title="银行证明材料" />
          <up-steps-item title="门店门头照片" />
          <up-steps-item title="审核状态" />
        </up-steps>
      </div>
      <div class="box_info">
        <div class="box_title">营业执照上传</div>
        <Upload :default-file="form.businessLicense" :file-style="{width: '65vw', height: '300rpx',margin:'30rpx 0 0rpx 80rpx'}" :is-before-upload-show-pop="true" update @file="form.businessLicense = $event">
          <Image :styles="{'margin':'30rpx 0 0 80rpx'}" height="300" name="businessLicenseBG" oss type="png" width="480" />
        </Upload>
        <div class="tip" style="margin: 16rpx 0 14rpx 80rpx;">支持上传：png、jpg、jpeg</div>
        <LabelAndValue :box-style="labelValueStyle" colon label="企业名称" label-width="210" required>
          <div :style="{color: form.name ? 'rgba(0,0,0,.45)' : 'rgba(0,0,0,.25)', height: '100%'}" class="flex_sb_cen">{{ form.name || '未获取' }}</div>
        </LabelAndValue>
        <LabelAndValue :box-style="labelValueStyle" colon label="法人姓名" label-width="210" required>
          <div :style="{color: form.legalPerson ? 'rgba(0,0,0,.45)' : 'rgba(0,0,0,.25)', height: '100%'}" class="flex_sb_cen">{{ form.legalPerson || '未获取' }}</div>
        </LabelAndValue>
        <LabelAndValue :box-style="labelValueStyle" colon label="企业类型" label-width="210" required>
          <div :style="{color: form.enterpriseType ? 'rgba(0,0,0,.45)' : 'rgba(0,0,0,.25)', height: '100%'}" class="flex_sb_cen">{{ form.enterpriseType || '未获取' }}</div>
        </LabelAndValue>
        <LabelAndValue :box-style="labelValueStyle" colon label="统一信用代码" label-width="230" required>
          <Input v-model:value="form.creditCode" :styles="{color: 'rgba(0,0,0,.45)'}" disabled placeholder="未获取" />
        </LabelAndValue>
        <LabelAndValue :box-style="labelValueStyle" colon label="经营所在地区" label-width="230" position="left" required>
          <div class="flex_sb_cen" style="height: 100%" @tap="selectSite" v-html="siteText" />
        </LabelAndValue>
        <LabelAndValue :box-style="!form.isSelfEnterprise ? labelValueStyle : {marginTop: '40rpx', height: '86rpx'}" colon label="详细地址" label-width="210" required>
          <Input v-model:value="form.address" placeholder="请输入详细地址" />
        </LabelAndValue>
        <template v-if="!form.isSelfEnterprise">
          <LabelAndValue :box-style="{marginTop: '40rpx', height: '86rpx'}" colon label="联系人" label-width="190" required>
            <div class="card_no" @tap="openContactDrewer">
              <div :style="{color: `rgba(0, 0, 0, 0.${form.linkMan ? '85' : '25'})`, paddingLeft: 0}" class="_placeholder">{{ contactText }}</div>
              <Icon :styles="{opacity: 0.5 }" name="icon-youjiantou" size="30" />
            </div>
          </LabelAndValue>
        </template>
      </div>
      <template v-if="!form.isSelfEnterprise">
        <div class="box_info">
          <div class="box_title">法人身份证上传</div>
          <!-- 身份证人像面 -->
          <template>
            <LabelAndValue :box-style="{marginTop: '20rpx'}" label="身份证-人像面" label-width="500" required />
            <Image
              v-if="form.legalPersonCardImgBack"
              :name="form.legalPersonCardImgBack"
              :styles="{border: '2rpx solid rgba(0, 0, 0, 0.15)', borderRadius: '20rpx', position: 'relative', margin: '20rpx 0 28rpx 80rpx'}"
              height="300"
              width="480"
            >
              <Icon
                :styles="{ position: 'absolute', top: '0', right: '0'}"
                name="icon-tupianguanbianniu"
                size="40"
                @tap="form.legalPersonCardImgBack = ''"
              />
            </Image>
            <Image v-else :styles="{margin: '20rpx 0 28rpx 80rpx'}" height="300" name="id_card_front" oss type="png" width="480" @tap="toIDViewFn('IDPersonImg')" />
          </template>
          <!-- 身份证国徽面-->
          <template>
            <LabelAndValue label="身份证-国徽面" label-width="500" required />
            <Image
              v-if="form.legalPersonCardImgFront"
              :name="form.legalPersonCardImgFront"
              :styles="{border: '2rpx solid rgba(0, 0, 0, 0.15)', borderRadius: '20rpx', position: 'relative', margin: '20rpx 0 0 80rpx'}"
              height="300"
              width="480"
            >
              <Icon
                :styles="{ position: 'absolute', top: '0', right: '0'}"
                name="icon-tupianguanbianniu"
                size="40"
                @tap="form.legalPersonCardImgFront = ''"
              />
            </Image>
            <Image v-else :styles="{margin: '20rpx 0 0 80rpx'}" height="300" name="id_card_back" oss type="png" width="480" @tap="toIDViewFn('IDFront')" />
          </template>
          <LabelAndValue :box-style="labelValueStyle" colon label="法人姓名" label-width="210" required>
            <Input v-model:value="form.legalPersonName" :styles="{color: 'rgba(0,0,0,.45)'}" disabled placeholder="未获取" />
          </LabelAndValue>
          <LabelAndValue :box-style="labelValueStyle" colon label="法人身份证" label-width="210" required>
            <Input v-model:value="form.legalPersonCardNo" :styles="{color: 'rgba(0,0,0,.45)'}" disabled maxlength="18" placeholder="未获取" />
          </LabelAndValue>
          <LabelAndValue :box-style="labelValueStyle" colon label="证件有效期" label-width="210" required>
            <div class="card_no">
              <div :style="{color: `rgba(0, 0, 0, 0.${form.idValidity ? '45' : '25'})`, paddingLeft: 0}" class="_placeholder">{{ cardText }}</div>
            </div>
          </LabelAndValue>
          <LabelAndValue :box-style="labelValueStyle" colon label="法人电话号码" label-width="230" required>
            <Input v-model:value="form.legalPersonPhone" maxlength="11" placeholder="请输入法人电话号码" />
          </LabelAndValue>
        </div>
        <div class="box_info">
          <div class="box_title" style="display: flex"><div style="color: red">*</div>授权书</div>
          <div class="tip">如营业执照法人信息与智客姓名不同，需上传授权书</div>
          <div class="tip flex_start mt10">
            <div class="flex_cen_cen base_color" style="margin-right: 62rpx" @tap.stop="downloadAuthorization">
              <Icon name="icon-xiazaidaoru" size="24" />
              <div style="margin-left: 5px">点击下载授权书模板</div>
            </div>
            <div class="flex_cen_cen base_color" @tap.stop="changeAuthorizationRef">
              <Icon name="icon-chakan-2" size="24" />
              <div style="margin-left: 5px">查看授权书样板</div>
            </div>
          </div>
          <div style="margin: 40rpx auto 42rpx 80rpx;">
            <Pupload :default-file="form.authPic" :is-change-img-show-position="true" :multiple="true" limit-count="3" limit-size="10" update width="560" @file="form.authPic = $event">
              <Image v-if="form.authPic?.length >= 3" height="350" name="shouquanshu_dark" oss type="png" width="560" />
              <Image v-else height="350" name="shouquanshu_bright" oss type="png" width="560" />
            </Pupload>
            <div class="tip">支持上传：png、jpg、jpeg</div>
          </div>
        </div>
      </template>
      <div :style="keepBottomSafeDis()" class="suction_bottom_btn">
        <Button :disabled="form.isSelfEnterprise ? !canSubmit1 : !canSubmit" size="L" @confirm="submitAuthFn">提交认证</Button>
      </div>
      <!--  经营所在地区  -->
      <Drawer ref="siteRef" mask>
        <SiteSelect @cancel="cancelSite" @value="setSite" />
      </Drawer>
      <!--时间选择弹框-->
      <Drawer ref="DateRef" mask>
        <DateSelect type="dates" @cancel="cancelDate" @value="DateChange" />
      </Drawer>
      <Drawer ref="ContactRef" mask>
        <StateSelect :config="recordConfig" title="请选择联系人" @cancel="ContactRef.change()" @value="confirmContactFn" />
      </Drawer>
      <Popup ref="legalPersonInfoCheckRef" mask>
        <Pconfirm
          cancel-text="返回修改"
          confirm-text="开始认证"
          tip-text="为了确保企业主体资料的真实有效，当前企业法人需要完成电子签约授权与人脸识别。请保持周围光线明亮，以便摄像头能够清晰获取您的脸部信息"
          tip-title="法人信息验证提醒"
          @cancel="legalPersonInfoCheckRef.change()"
          @confirm="startFn"
        />
      </Popup>
      <!-- 授权书模板预览 -->
      <Popup ref="AuthorizationRef" mask>
        <div class="authorization_temp">
          <Image height="830" name="document_doc/GL授权委托书模板" oss style="margin: auto" type="png" width="600" />
        </div>
      </Popup>
      <!--  营业执照法人不同智客提示  -->
      <u-popup :close-on-click-overlay="false" :show="isShowAuthTip" bg-color="transparent" mode="center" overlay-opacity="0.25">
        <Pconfirm
          :styles="{width: '670rpx',borderRadius: '24rpx', paddingRight: '24rpx', paddingLeft: '26rpx'}"
          tip-title="提示"
        >
          <template #tip>
            <div class="tip_content">企业资料正在认证，请继续填写</div>
            <div class="tip_content">请法人查看手机短信，点击链接完成企业认证</div>
          </template>
          <template #twoBtn>
            <div class="flex_sb_cen" style="width: 100%">
              <Button :styles="{width: '292rpx'}" type="solid" @confirm="isShowAuthTip = false">取消</Button>
              <Button :styles="{width: '292rpx'}" @confirm="continueFn">继续填写</Button>
            </div>
          </template>
        </Pconfirm>
      </u-popup>
      <!--  营业执照被使用弹窗  -->
      <u-popup :close-on-click-overlay="false" :show="showBusinessLicenseUsed" bg-color="transparent" mode="center" overlay-opacity="0.25">
        <Pconfirm :is-two-btn="false" :tip-text="tipText" confirm-text="我知道了" tip-title="提示" @confirm="showBusinessLicenseUsed = false" />
      </u-popup>
    </div>
  </scroll-view>
</template>
<script lang="ts" setup>
import { computed, reactive, ref, watch } from 'vue'
import Upload from '@C/Upload.vue'
import Image from '@C/Image.vue'
import LabelAndValue from '@C/LabelAndValue.vue'
import Input from '@C/Input.vue'
import Icon from '@C/Icon.vue'
import Pupload from '@C/Pupload.vue'
import Button from '@C/Button.vue'
import { keepBottomSafeDis, bottomStaySpace, Router, storeState, onLoad, checkPhoneFn } from '@U/common'
import { Msg, MsgLoading, PMsgLoadingClean } from '@C/Msg'
import { ocr_idCardBack, ocr_idCardFront, ocr_license } from '@P/Auth/request'
import Drawer from '@C/Drawer.vue'
import SiteSelect from '@C/SiteSelect.vue'
import DateSelect from '@C/DateSelect.vue'
import StateSelect from '@C/StateSelect.vue'
import {
  createThirdEnterpriseFirstStep,
  getExternalEnterprisesInfo,
  modifyThirdEnterpriseFirstStep,
} from '@P_GL/holdMainBody/request'
import Pconfirm from '@C/Pconfirm.vue'
import Popup from '@C/Popup.vue'
import type { IObj } from '@/interface'

const form = reactive({
  id: '',
  businessLicense: '',
  name: '',
  isSelfEnterprise: true, // 外部企业是不是智客本人的企业，默认是
  province: '',
  provinceCode: '',
  city: '',
  cityCode: '',
  district: '',
  districtCode: '',
  address: '',
  creditCode: '',
  legalPersonCardImgFront: '',
  legalPersonCardImgBack: '',
  legalPersonName: '',
  legalPerson: '',
  enterpriseType: '',
  legalPersonCardNo: '',
  idValidity: '',
  legalPersonPhone: '',
  legalPersonCardType: 5001,
  linkMan: '',
  authPic: [],
  registeredCapital: '',
  businessAddress: '',
  businessLicenceValidityStart: '',
  businessLicenceValidity: '',
  longTimeOrNo: false,
  coopStatus: 0,
  profileStatus: 0,
})
// 组件样式
const labelValueStyle = { borderBottom: '1rpx solid rgba(0,0,0,0.1)', height: '86rpx', marginTop: '40rpx', paddingRight: 0 }
// 经营所在地区
const siteText = computed(() => (form.district ? `${form.province}/${form.city}/${form.district}` : '<span style="color: rgba(0, 0, 0, 0.25)">请选择经营所在地区</span>'))
// 选择省市区
const siteRef = ref()
const selectSite = () => siteRef.value.change()
const setSite = (e: IObj) => {
  form.province = e?.province.name
  form.city = e?.city.name
  form.district = e?.district.name
  form.provinceCode = e?.province.code
  form.cityCode = e?.city.code
  form.districtCode = e?.district.code
  selectSite()
}
const cancelSite = () => siteRef.value.change()
// 证件有效期显示文本
const cardText = computed(() => (form.idValidity?.slice(0, 21) || '未获取'))
const contactText = ref('请选择联系人')
// 身份证日期选择
const DateRef = ref()
// 打开日期弹框
// const openDateDrewer = () => { DateRef.value.change() }
const cancelDate = () => { DateRef.value.change() }
const DateChange = (date: string[]) => {
  let cardExpdate = ''
  date.forEach((i: string) => { cardExpdate += `${i}-` })
  form.idValidity = cardExpdate.substring(0, 21)
  DateRef.value.change()
}

// 联系人选择
const ContactRef = ref()
const recordConfig = ref([
  { label: '同智客信息', value: '0' },
  { label: '同法人信息', value: '1' },
])
const openContactDrewer = () => { ContactRef.value.change() }
const confirmContactFn = (e: any, obj: any) => {
  ContactRef.value.change()
  contactText.value = obj.label
  form.linkMan = obj.value
}

const toIDViewFn = (side: string) => Router.push('ID_Viewfinder', { side, cardType: '5001' })

// 以下两个属性用于判断：当 form.isSelfEnterprise 为 false 时，上传的法人身份信息 和 营业执照法人信息 是否相同
const businessPersonName = ref('')
const manualCardName = ref('')
let tempBusinessLicenceNo = ''
// 营业执照OCR
watch(
    () => form.businessLicense,
    async (newVal: string) => {
      if (newVal) {
        await MsgLoading('识别中')
        const res = await ocr_license({ imgPath: newVal }).finally(() => {})
        if (res?.code === 200) {
          PMsgLoadingClean()
          // 法大大驳回&企业通过审核，进入判断
          if (form.profileStatus === 3 && form.coopStatus === 2) {
            tempBusinessLicenceNo = res.data?.businessLicenceNo // 用于下面提交时最后一道防线
            if (form.creditCode !== res.data?.businessLicenceNo) return Msg({ msg: '统一社会信用代码不一致，请重新上传', duration: 3000 })
          }
          form.name = res.data?.companyName || ''
          form.creditCode = res.data?.businessLicenceNo || ''
          form.enterpriseType = res.data?.enterpriseType || '个体工商户'
          form.registeredCapital = res.data?.registeredCapital || ''
          form.businessAddress = res.data?.businessAddress || ''
          form.businessLicenceValidityStart = res.data?.buildDate || ''
          form.businessLicenceValidity = res.data?.businessLicenceValidity || ''
          form.longTimeOrNo = !res.data?.businessLicenceValidityStart
          form.legalPerson = res.data?.legalPerson
          // 营业执照法人代表 和 智客姓名相同时，直接从 vuex 里取 智客信息；不同时，身份信息，需要靠手动上传来获取
          if (storeState.zhiKeInfo?.name === res.data?.legalPerson) {
            form.legalPersonCardImgBack = storeState.zhiKeInfo?.cardImgBack
            form.legalPersonCardImgFront = storeState.zhiKeInfo?.cardImgFront
            form.legalPersonCardNo = storeState.zhiKeInfo?.cardNo
            form.idValidity = storeState.zhiKeInfo?.idValidity
            form.legalPersonPhone = storeState.zhiKeInfo?.mobile
            form.legalPersonName = storeState.zhiKeInfo?.name
            form.linkMan = '0'
            contactText.value = '同智客信息'
            form.isSelfEnterprise = true
          } else {
            businessPersonName.value = res.data?.legalPerson || ''
            form.isSelfEnterprise = false
          }
        }
      }
    },
)
watch(
    () => storeState.routeParams,
    (newVal) => {
      if (newVal._path) {
        if (newVal.IDSide === 'IDPersonImg') form.legalPersonCardImgBack = newVal._path
        else form.legalPersonCardImgFront = newVal._path
      }
    },
)
// 身份证OCR
watch(
    () => form.legalPersonCardImgBack,
    async (newVal: string) => {
      if (newVal) {
        await MsgLoading('识别中')
        const res = await ocr_idCardBack({ imgPath: newVal }).finally(() => {})
        if (res?.code === 200) {
          PMsgLoadingClean()
          if (res.data) {
            const { trueName, cardNo } = res.data
            form.legalPersonCardNo = cardNo
            form.legalPersonName = trueName
            manualCardName.value = trueName
          } else {
            form.legalPersonCardNo = ''
            form.legalPersonName = ''
            manualCardName.value = ''
          }
        }
      }
    },
)
watch(
    () => form.legalPersonCardImgFront,
    async (newVal: string) => {
      if (newVal) {
        await MsgLoading('识别中')
        const res = await ocr_idCardFront({ imgPath: newVal }).finally(() => {})
        if (res?.code === 200) {
          if (res.data) {
            const { cardExpdate, cardIssuedDate } = res.data
            form.idValidity = `${cardIssuedDate}-${cardExpdate}`
          } else form.idValidity = ''
        }
      }
    },
)
// 下载授权书模板并分享
const downloadAuthorization = () => {
  uni.downloadFile({
    url: `${import.meta.env.VITE_SHOUDAO_OSS_URL}/document_doc/GLPowerOfAttorneyTemplate.docx`,
    success(res) {
      wx.shareFileMessage({
        filePath: res.tempFilePath,
        fileName: '授权书模板.docx',
        success() {
        },
        fail(error: IObj) {
          console.log('error', error)
        },
      })
    },
  })
}
// 查看授权书模板
const AuthorizationRef = ref()
const changeAuthorizationRef = () => { AuthorizationRef.value?.change() }
// const watchAuthorizationFn = () => {
//   uni.previewImage({})
// }
// 提交
const canSubmit = computed(() => (
    // 营业执照法人信息和智客信息不同时，需满足两个条件：
    // 1. 上传法人身份证 和 授权书；
    // 2. 上传的法人身份信息 和 营业执照法人信息 必须是同一个；
    form.name
    && form.businessLicense
    && form.legalPerson
    && form.enterpriseType
    && form.creditCode
    && form.province
    && form.city
    && form.district
    && form.provinceCode
    && form.cityCode
    && form.districtCode
    && form.address
    && form.legalPersonCardImgBack
    && form.legalPersonCardImgFront
    && form.legalPersonName
    && form.legalPersonCardNo
    && form.legalPersonPhone
    && form.linkMan
    && form.idValidity
    && form.authPic.length > 0
))
const canSubmit1 = computed(() => (
    form.name
    && form.businessLicense
    && form.legalPerson
    && form.enterpriseType
    && form.creditCode
    && form.province
    && form.city
    && form.district
    && form.provinceCode
    && form.cityCode
    && form.districtCode
    && form.address
))
const legalPersonInfoCheckRef = ref()
const startFn = () => {
  legalPersonInfoCheckRef.value.change()
}
const isShowAuthTip = ref(false)
const tipText = ref('')
const showBusinessLicenseUsed = ref(false)
const submitAuthFn = async () => {
  if (form.isSelfEnterprise) {
    if (!canSubmit1.value) return
  } else {
    if (!canSubmit.value) return
    if (businessPersonName.value !== manualCardName.value) return Msg({ msg: '营业执照法人信息和法人身份信息必须相同' })
    if (!checkPhoneFn(form.legalPersonPhone)) return Msg({ msg: '法人电话号码格式不正确' })
  }
  if (!form.name || !form.creditCode || !form.enterpriseType || !form.businessAddress || !form.businessLicenceValidityStart) return Msg({ msg: '营业执照识别错误，请上传完整信息的照片', duration: 3000 })
  // 法大大驳回&企业通过审核，进入判断
  if (form.profileStatus === 3 && form.coopStatus === 2) {
    if (form.creditCode !== tempBusinessLicenceNo) return Msg({ msg: '统一社会信用代码不一致，请重新上传', duration: 3000 })
  }
  await MsgLoading('提交中')
  let res = {}
  if (form.id) res = await modifyThirdEnterpriseFirstStep(form).finally(() => {})
  else res = await createThirdEnterpriseFirstStep(form).finally(() => {})
  if (res?.code === 200) {
    form.id = res.data
    return commonFn()
  }
  if (res?.code === 212) {
    PMsgLoadingClean()
    tipText.value = res.msg
    showBusinessLicenseUsed.value = true
  }
}
const commonFn = () => {
  PMsgLoadingClean()
  // 企业资料已通过  注：法大大被驳回时，企业审核状态不可能为 1 或 3。因为只有当法大大审核通过，提交的企业资料状态才会变成1
  if (form.coopStatus === 2) return Router.back(2)
  // 营业执照法人同智客
  if (form.isSelfEnterprise) {
    Msg({ msg: '认证中，请继续填写' })
    setTimeout(() => {
      Router.redirect('new_add_bank_prove_material', { id: form.id })
    }, 1000)
  } else {
    // 营业执照法人不同智客
    isShowAuthTip.value = true
  }
}
const continueFn = () => {
  isShowAuthTip.value = false
  Router.redirect('new_add_bank_prove_material', { id: form.id })
}
// 获取外部其他企业信息
const getExternalEnterprisesInfoFn = async (id: string) => {
  const res = await getExternalEnterprisesInfo({ id }).finally(() => {})
  if (res?.code === 200) {
    res.data.linkMan = res.data.linkMan?.toString() // 将数字转成字符串
    contactText.value = res.data.linkMan === '0' ? '同智客信息' : res.data.linkMan === '1' ? '同法人信息' : '请选择联系人'
    for (const key in form) {
      form[key] = res.data[key]
    }
  }
}
onLoad((option: any) => {
  if (option.id) {
    getExternalEnterprisesInfoFn(option.id)
  }
})
</script>

<style lang="less" scoped>
.wrap {
  height: 100vh;
  /deep/ .u-steps {
    display: flex;
  }
  .step {
    padding: 28rpx 0;
    margin-top: 2rpx;
    background-color: #fff;
    /deep/ .u-steps-item__wrapper__circle {
      width: 52rpx;
      height: 52rpx;
      border-radius: 50%;
    }
    /deep/ .u-text__value--content {
      color: #DEDFE2;
    }
    /deep/ .u-steps-item__wrapper--row {
      width: auto;
    }
    /deep/ .u-text__value {
      font-size: 24rpx !important;
    }
    /deep/ .u-text__value--main {
      color: #1890FF;
    }
  }
  .box_info {
    background: #FFFFFF;
    padding: 20rpx 40rpx 45rpx;
    box-sizing: border-box;
    margin-top: 20rpx;
    .box_title {
      font-size: 32rpx;
      font-weight: 500;
      color: rgba(0,0,0,0.85);
      line-height: 44rpx;
    }
    .tip {
      height: 32rpx;
      font-size: 24rpx;
      color: #8c8c8c;
    }
    .card_no_switch{
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content:flex-end;
      margin: 20rpx 15rpx;
      .switch_content {
        width: 112rpx;
        height: 44rpx;
        font-weight: 400;
        color: rgba(0,0,0,0.65);
        line-height: 44rpx;
        margin: 0 20rpx;
      }
    }
    .card_no {
      font-size: 28rpx;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      ._placeholder {
        padding-left: 16rpx;
      }

    }
  }
  .authorization_temp {
    width: 600rpx;
    .authorization_cancel {
      position: absolute;
      top: 10%;
      right: 20rpx;
    }
  }
  .tip_content {
    font-weight: 400;
    text-align: left;
    color: rgba(0,0,0,0.85);
    line-height: 40rpx;
    padding: 0 24rpx 0 26rpx;
  }
}
</style>
